AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')

function ENT:Initialize()
	self.BaseClass.Initialize(self)
	self.dt.Power = self.Power
	self.PoweredEntSlots = {} //structures this power plant is powering
end

function ENT:Use(activator, caller)
	if self.dt.Owner:CanAfford(self.PowerCost) && (activator == self.dt.Owner || IsAllied(activator, self.dt.Owner)) then
		self:CreateTimers()
		self.Active = true
		self:SetColor(255, 255, 255, 255)
	end
end

function ENT:TurnOff()
	self.BaseClass.TurnOff(self)
	
	for k, ent in pairs(self.PoweredEntSlots) do
		ent.dt.Power = 0
		self.dt.Power = self.dt.Power + 1
	end
end

function ENT:ChargeForPower()
	if self.Active && self.dt.Owner:CanAfford(self.PowerCost) then
		local owner = self.dt.Owner
		owner:TakeMoney(self.PowerCost)
		Notify(owner, 0, 3, string.format("Charged $%i to keep a generator running.", self.PowerCost))
	else
		self:TurnOff()
	end
end

function ENT:ScanForStructures()
	if self.Active then
		local EntsAroundPlant = ents.FindInSphere(self:GetPos(), self.PowerDistance)
		
		for k, ent in pairs(self.PoweredEntSlots) do
			if ValidEntity(ent) then
				if !table.HasValue(EntsAroundPlant, ent) then
					table.remove(self.PoweredEntSlots, k)
					ent.dt.Power = ent.dt.Power - 1
					self.dt.Power = self.dt.Power + 1
				end
			else
				table.remove(self.PoweredEntSlots, k)
				self.dt.Power = self.dt.Power + 1
			end
		end
		
		if self.dt.Power > 0 then //in the future there won't be three of these :D
			for k, ent in pairs(EntsAroundPlant) do
				if self.dt.Power > 0 && ent.Structure && ent.ClassName != "struct_powerplant" && ent.Power > 0 && ent.dt.Power < ent.Power then
					for i = 1, (ent.Power - ent.dt.Power) do
						if self.dt.Power > 0 then
							self.dt.Power = self.dt.Power - 1
							ent.dt.Power = ent.dt.Power + 1
							table.insert(self.PoweredEntSlots, ent)
						end
					end
				end
			end
		end
		
		/*
		PrintTable(self.PoweredEntSlots)
		print(self.dt.Power)
		print("\n")
		*/

	end
end

function ENT:CreateTimers()
	timer.Create(tostring(self) .. "scanforstructures", 1, 0, self.ScanForStructures, self)
	timer.Create(tostring(self) .. "chargeforpower", self.PowerCostTime, 0, self.ChargeForPower, self)
	timer.Create(tostring(self) .. "warnturnoff", self.TurnOffTime - (self.TurnOffTime * 0.1), 1, self.WarnTurnOff, self)
	timer.Create(tostring(self) .. "turnoff", self.TurnOffTime, 1, self.TurnOff, self)
end

function ENT:OnRemove()
	for k, ent in pairs(self.PoweredEntSlots) do
		ent.dt.Power = 0
		self.dt.Power = self.dt.Power + 1
	end

	timer.Remove(tostring(self) .. "scanforstructures")
	timer.Remove(tostring(self) .. "chargeforpower")
	timer.Remove(tostring(self) .. "warnturnoff")
	timer.Remove(tostring(self) .. "turnoff")
end